<template>
  <!-- 关口表 配置 -->
  <a-form
    :model="form"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    layout="vertical"
    ref="formRef"
    :rules="rules"
    :disabled="!configData.isEdit"
  >
    <a-form-item label="关口表名称" name="name">
      <a-input
        v-model:value="form.name"
        class="formInput"
        placeholder="关口表名称"
      />
    </a-form-item>
    <a-form-item
      label="关口表资产编码"
      placeholder="关口表资产编码"
      name="assetCode"
    >
      <a-input v-model:value="form.assetCode" class="formInput" disabled />
    </a-form-item>
    <a-form-item label="数据来源" name="sourceId">
      <a-select
        class="formSelect"
        v-model:value="form.sourceId"
        placeholder="数据来源"
      >
        <a-select-option
          v-for="item in energyLinkList"
          :value="item.deviceId"
          :key="item.deviceId"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
    </a-form-item>
  </a-form>
  <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
    <a-button v-if="!configData?.isEdit" type="primary" @click="handleEdit"
      >编辑</a-button
    >
    <a-button
      v-else
      type="primary"
      @click="onSubmit"
      :loading="stionConfigState.configDataSaveLoading"
      >保存</a-button
    >
  </a-form-item>
</template>
<script setup>

import { EQUIP_TYPE } from "@/constants/stationConfig";
import { useStionConfigStore } from "@/stores/stationConfig";
const { stionConfigState, changeConfigData } = useStionConfigStore();
const configData = computed(() => stionConfigState.configData);
const emits = defineEmits(["getConfig"]);
import { cloneDeep } from "lodash-es";
const props = defineProps({
  rowData: {
    type: Object,
  },
  elements: {
    type: Array,
  },
});
watch(
  () => stionConfigState.configData,
  (val) => {
    form.value = cloneDeep(stionConfigState.configData);
  },
  { deep: true }
);
const $api = inject("$api");
const form = ref({
  name: null,
  assetCode: null,
  sourceId: null,
  type: EQUIP_TYPE.GUAN_KOU_BIAO,
});
const rules = ref({
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: "blur",
    },
  ],
  assetCode: [
    {
      required: true,
      message: "请输入",
      trigger: "blur",
    },
  ],
  sourceId: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
});
const formRef = ref();

// 查找当前关口表的父级变压器systemId
const findParentTransformerSystemId = () => {
  const currentDragData = stionConfigState.dragData;
  if (!currentDragData || !currentDragData.id) {
    return null;
  }
  const findElementInTree = (elements, targetId) => {
    for (const element of elements) {
      // 检查当前元素
      if (element.id === targetId) {
        return element;
      }
      if (element.children && element.children.length > 0) {
        const found = findElementInTree(element.children, targetId);
        if (found) {
          return found;
        }
      }
    }
    return null;
  };
  // 查找当前关口表元素
  const currentElement = findElementInTree(props.elements, currentDragData.id);
  if (currentElement && currentElement.parentId) {
    // 查找父级元素
    const findElementBySystemId = (elements, systemId) => {
      for (const element of elements) {
        if (element.systemId === systemId) {
          return element;
        }
        if (element.children && element.children.length > 0) {
          const found = findElementBySystemId(element.children, systemId);
          if (found) {
            return found;
          }
        }
      }
      return null;
    };
    const parentElement = findElementBySystemId(
      props.elements,
      currentElement.parentId
    );
    // 验证父级是否为变压器
    if (parentElement && parentElement.type === EQUIP_TYPE.BIAN_YA_QI) {
      return parentElement.systemId;
    }
  }

  return null;
};

const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      form.value.type = stionConfigState?.equipType;
      // 查找并设置父级变压器的systemId，后端需要带上这个变压器id字段
      const parentTransformerSystemId = findParentTransformerSystemId();
      form.value.parentId = parentTransformerSystemId;
      emits("getConfig", toRaw(form));
    })
    .catch((error) => {
      console.log("error", error);
    });
};
const labelCol = { style: { width: "150px" } };
const wrapperCol = { span: 14 };
const handleEdit = () => {
  changeConfigData({
    ...stionConfigState.configData,
    isEdit: true,
  });
};
const energyLinkList = ref([]);
const getEnergyLinkPage = async () => {
  // 获取电池堆列表 如果不是主电池堆，需要拉取电池堆列表指定所属
  const res = await $api.energyLinkList({
    stationId: props.rowData.stationId,
  });
  energyLinkList.value = res?.data;
};
onMounted(async () => {
  await getEnergyLinkPage();
});
</script>
<style lang="less" scoped>
.formInput {
  width: 175px;
}
.formSelect {
  width: 175px;
  text-align: left;
}
</style>